<?php

namespace app\api\service;

use app\common\model\Order;
use app\common\model\OrderItem;
use app\common\model\Product;
use app\common\model\Product as ProductModel;

class ProductService extends BaseService
{

    /**
     * 商品提交生成订单
     * @param Product $product
     * @param $qty
     * @param $userId
     * @return false|string
     */
    public function submitOrder(Product $product, $qty, $userId)
    {

        $discountAmount = 0;
        $content = '';
        $remark = '';

        $price = $product['price'];
        $amount = bcmul($price, $qty, 2);
        $order = new OrderService();

        $orderRes = $order->submit(Order::TYPE_PRODUCT, $userId, $amount, $discountAmount);
        if (empty($orderRes)) {
            $this->setMsg($order->getMsg());
            return false;
        }

        $orderItem = new OrderItemService();
        $resItem = $orderItem->submit($orderRes->id, $product['id'], OrderItem::DATA_TYPE_PRODUCT, $product['name'], $qty, $price, $discountAmount, $content, $remark);
        if (empty($resItem)) {
            $this->setMsg($orderItem->getMsg());
            return false;
        }
        $orderRes['order_item'] = $resItem;

        return $orderRes;
    }

    /**
     * 获取商品列表 (Ids)
     * @param int|string $product_ids
     * @return Product|false
     */
    public function getProductById($product_id)
    {
        // 检查 product_id
        $product = ProductModel::get([
            'id' => $product_id,
        ]);
        if (!$product) {
            return $this->setMsg('product_id错误');
        }
//        if ($product['status'] !== ProductModel::STATUS_ON) {
//            return $this->setMsg("商品{$product['name']}已下架");
//        }
        return $product;
    }

    /**
     * 获取商品列表 (Ids)
     * @param array $product_ids
     * @return array|false
     */
    public function getProductsByIds(array $product_ids)
    {
        // 检查 product_id
        $products = ProductModel::all([
            'id' => ['in', $product_ids],
        ]);
        if (!$products) {
            return $this->setMsg('product_id错误');
        }
        $products = collection($products)->column(null, 'id');
        foreach ($product_ids as $product_id) {
            if (empty($products[$product_id])) {
                return $this->setMsg("product_id[{$product_id}]不存在");
            }
//            if ($products[$product_id]['status'] !== ProductModel::STATUS_ON) {
//                return $this->setMsg("[{$products[$product_id]['name']}] 已下架");
//            }
        }
        return $products;
    }
}
